home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 616 < prev    next >
Encoding:
Internet Message Format  |  1996-08-06  |  1.6 KB

  1. Path: news.mira.net.au!news
  2. From: davidw@werple.net.au (David White)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Creating a pointer to a function "void (*ptrFunction)()" inside a class
  5. Date: 5 Jan 1996 23:06:51 +1100
  6. Organization: Werple Internet, Melbourne
  7. Message-ID: <4cj48r$kq0@werple.net.au>
  8. References: <30ECA10F.3D99@ifu.net> <4civ47$hg6@werple.net.au>
  9. NNTP-Posting-Host: werple.mira.net.au
  10.  
  11. davidw@werple.net.au (David White) writes:
  12.  
  13.  
  14. >    class BaseClass
  15. >    {
  16. >    protected:
  17. >        // A typedef simplifies things somewhat. 
  18. >     // Also, the correct function parameters (int, int) are required
  19. >        typedef int (BaseClass::*FPTR)(int, int);
  20. >        FPTR ptrFunction;
  21. >    };
  22.  
  23. >    class DerivedClass : BaseClass
  24. >    {
  25. >    public:
  26. >        DerivedClass()
  27. >    { ptrFunction = (FPTR)&DerivedClass::myFunction; 
  28. >    }
  29. >    int myFunction(int, int);
  30. >    }
  31.  
  32. I should add a warning about this code. In some circumstances the value of
  33. 'this' is not the same for the base class and the derived class. For
  34. example, using my compiler, a difference in values would occur if I added
  35. a virtual function to DerivedClass, and there are no virtual functions in
  36. BaseClass. So, because the function pointer is declared as pointing to a
  37. BaseClass function, 'myFunction' will not receive the correct DerivedClass
  38. 'this' pointer. The problem can be corrected, on my compiler at least, by
  39. ensuring that BaseClass has at least one virtual function if any of its
  40. derived classes do also, but I don't know if you can count on that for
  41. other compilers. Multiple inheritance can also cause this problem.
  42.  
  43. David White
  44. davidw@werple.mira.net.au
  45.